/*TCP Server Program using Berkley Sockets*/

/* Compile Command: cc -o tcps tcps.c -lnsl -lsocket */
/* Run Command: ./tcps */

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>	// exit call
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>

#define SERVER_PORT 5488
#define MAX_PENDING 5
#define MAX_LINE 256

int main()
{
	struct sockaddr_in sin;
	char buf[MAX_LINE];
	int len;
	int s, new_s;
	len=sizeof(sin);

	bzero((char *)&sin, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(SERVER_PORT);

	// This gets a socket to work with
	if ((s = socket(PF_INET,SOCK_STREAM,0)) < 0)
	{
		perror("simplex-talk:socket not created");
		exit(1);
	}

	// bind the address with the socket
	if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0)
	{
		perror("simplex-talk: bind error");
		exit(1);
	}

	// listen on the socket
	listen(s,MAX_PENDING);
	len=sizeof(sin);

	while(1)
	{
		// accept connections
		if ((new_s = accept(s, (struct sockaddr *)&sin, &len)) < 0)
		{
			perror("simplex-talk:accept error");
			exit(1);
		}
		// receive data
		while (len = recv(new_s, buf, sizeof(buf), 0))
			fputs(buf,stdout);
		close(new_s);
	}
}
